﻿using UnityEngine;
using System.Collections;

public class IncomeTowerBehavior : MonoBehaviour {

	public Player owner;
	private Player neutral;
	private int income = 2;
	private float incomeMultiplier = 1f;
	private float timer = 0f;
	private float gameLength = 0f;
	private ArrayList nearbyUnits = new ArrayList ();

	// Use this for initialization
	void Start () 
	{
		owner = (Player) (GameObject.Find ("Neutral AI").GetComponent("Player"));
		neutral = (Player)(GameObject.Find ("Neutral AI").GetComponent ("Player"));
		nearbyUnits = new ArrayList();
	}
	
	// Update is called once per frame
	void Update () 
	{
		gameLength += Time.deltaTime;
		if((gameLength/180) >= 1)
		{
			gameLength = 0;
			incomeMultiplier *= 1.5f;
		}
		if(owner!=neutral)
		{
			timer += Time.deltaTime;
			if(timer >= 1)
			{
				owner.gold += (int) (income * incomeMultiplier);
				timer = 0;
			}
		}
		int i = 0;
		while(i < nearbyUnits.Count)  
		{
			Unit u = (Unit) nearbyUnits[i];
			if(!u.isDead ())
				i++;
			else
				nearbyUnits.Remove(u);
		}
	}

	void OnTriggerExit(Collider other)
	{
		foreach(Unit u in nearbyUnits)
		{
			if(u.Equals ((Unit) other.gameObject.transform.parent.gameObject.GetComponent ("Unit")))
			{
				nearbyUnits.Remove (u);
				break;
			}
		}
	}

	void ChangeOwner(Collider other)
	{
		bool changeOwner = true;
		
		if((other.gameObject.transform.parent!=null &&
		    other.gameObject.transform.parent.gameObject.GetComponent ("Unit") != null))
		{
			Unit u = (Unit)other.gameObject.transform.parent.gameObject.GetComponent ("Unit");
			if(!(owner.Equals (u.owner)))
			{
				foreach(Unit unt in nearbyUnits)
				{
					if(unt.owner.Equals (owner))
					{
						changeOwner = false;
					}
				}
			}
			else changeOwner = false;
			if(changeOwner == true)
			{
				owner = (Player) u.owner;
				foreach(Renderer o in this.gameObject.GetComponentsInChildren<Renderer>())
				{
					o.material.color=owner.myColor;
				}
			}
		}
	}

	void OnTriggerStay(Collider other)
	{
		ChangeOwner (other);
	}

	void OnTriggerEnter(Collider other)
	{
		ChangeOwner (other);	
	}
}